//
//  SafePayViewController.m
//  SXH
//
//  Created by Ryan on 16/3/19.
//  Copyright © 2016年 lyss. All rights reserved.
//

#import "SafePayViewController.h"
#import "ALiPay.h"
#import "WXPay.h"
#import "CommonService.h"
#import "OrderViewController.h"
//价格随时间变动，请在xx分钟内完成支付！
@interface SafePayViewController ()

@property (nonatomic,assign)NSInteger second;
@property (nonatomic,assign)NSString * payWay;
@end

@implementation SafePayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.941 green:0.941 blue:0.941 alpha:1.00];
    self.second = 48 * 60;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countTime) userInfo:nil repeats:YES];
    [timer fire];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePayResult:) name:@"ORDER_PAY_NOTIFICATION" object:nil];//监听一个通知

    
    self.OrderID.text = [NSString stringWithFormat:@"【产品编号：%@】%@",self.tourismDetailsEntity.t_id,self.tourismDetailsEntity.t_name];
    self.selectTimeLabel.text = [NSString stringWithFormat:@"<%@>",_selectTime];
    self.orderIDlabel2.text = self.orderIdString;
    self.selectTimeLabel2.text = self.selectTime;
    self.travelPerson.text = self.personString;
    self.ticketHolderName.text = self.ticketHolderNameString;
    self.ticketHolderPhone.text = self.ticketHolderPhoneString;
    self.payWay = @"1";
    self.priceLabel.text = [NSString stringWithFormat:@"¥ %@",[_order_dictionary objectForKey:@"total_amount"]];

}

- (void)countTime
{
    self.second -- ;
    NSString *headString = [NSString stringWithFormat:@"价格随时间变动，请在%zi:%zi内完成支付！",self.second/60,self.second%60];
    NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:headString];
    //获取要调整颜色的文字位置,调整颜色
    NSRange range1=[[hintString string]rangeOfString:@"价格随时间变动，请在"];
    [hintString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range1];
    NSRange range2=[[hintString string]rangeOfString:@"完成支付！"];
    [hintString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range2];
    
    self.headLabel.attributedText=hintString;
}

- (IBAction)aLipayfunc:(id)sender
{
    if(!self.ALiPay.selected)
    {
        self.WeiXinPay.selected = false;
        self.ALiPay.selected = true;
        self.payWay = @"1";
    }
    [self.ALiPay setImage:[UIImage imageNamed:K_trade_OK_imageName] forState:UIControlStateSelected];
    [self.WeiXinPay setImage:[UIImage imageNamed:K_trade_default_imageName] forState:UIControlStateNormal];
}


- (IBAction)weiXinPayfunc:(id)sender
{
    if(!self.WeiXinPay .selected){
        self.ALiPay.selected = false;
        self.WeiXinPay.selected = true;
        self.payWay = @"2";
    }
    [self.WeiXinPay setImage:[UIImage imageNamed:K_trade_OK_imageName] forState:UIControlStateSelected];
    [self.ALiPay setImage:[UIImage imageNamed:K_trade_default_imageName] forState:UIControlStateNormal];
}

- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)gotoPay:(id)sender
{
    CommonService *service = [[CommonService alloc]init];
    NSDictionary * parm = @{@"user_id":USERID,
                            @"order_num":self.orderIdString,
                            @"pay_type":self.payWay};
    [service getNetWorkData:parm Path:USER_ORDER_PAYTYPE Successed:^(NSMutableDictionary* entity) {
        if(self.ALiPay.selected){
            //TODO:支付宝创建订单
            ALiPay *alipay=[[ALiPay alloc]init];
            float _total_amount = [[NSString stringWithFormat:@"%@",[self.order_dictionary objectForKey:@"total_amount"]] floatValue];
            [alipay postOrder:[self.order_dictionary objectForKey:@"order_num"] productName:AppName productDescription:OrderSubmit amount:[NSString stringWithFormat:@"%.2f",_total_amount] VC:self  orderFlag:@"new"];
        }else if(self.WeiXinPay.selected){
            //TODO:微信创建订单
            WXPay *wxPay=[[WXPay alloc]init];
            //本地处理签名
            //                                  [wxPay sendPay:[dic objectForKey:@"order_num"] productName:@"乐游山水" amount:@"1" VC:self];
            //服务器端处理签名
//            self.
            [self.order_dictionary setValue:[entity valueForKey:@"prepayId"] forKey:@"prepayId"];
            [self.order_dictionary setValue:[entity valueForKey:@"nonceStr"] forKey:@"nonceStr"];
            [self.order_dictionary setValue:[entity valueForKey:@"sign"] forKey:@"sign"];
            [self.order_dictionary setValue:[entity valueForKey:@"timeStamp"] forKey:@"timeStamp"];

            [self.order_dictionary addEntriesFromDictionary:entity];
            [wxPay sendPay:self.order_dictionary VC:self];
        }

    } Failed:^(NSInteger errorCode, NSString *message) {
        
    }];
    dispatch_async(dispatch_get_main_queue(), ^{
            //TODO: 保存订单号
//            [self orderInfo:[dic objectForKey:@"order_num"]qty:labQty.text];
        
    });
}

-(void)handlePayResult:(id)code{
    OrderViewController *vc=[[OrderViewController alloc]init];
    vc.userId=USERID;
    if([code isKindOfClass:[NSString class]]){
        if([code isEqualToString:@"6001"]){
            ALERT_ERR_MSG(PayCanceled);
            vc.orderFlag=NO;
        }
        if([code isEqualToString:@"9000"]){
            ALERT_ERR_MSG(PaySuccess);
            vc.orderFlag=YES;
        }
    }else{
        if([[code valueForKey:@"object"] isEqualToString:@"6001"]){
            ALERT_ERR_MSG(PayCanceled);
            vc.orderFlag=NO;
        }
        if([[code valueForKey:@"object"] isEqualToString:@"9000"]){
            ALERT_ERR_MSG(PaySuccess);
            vc.orderFlag=YES;
        }
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}

//- (void)setOrder_dictionary:(NSMutableDictionary *)order_dictionary
//{
//    _order_dictionary = order_dictionary;
//
//}
@end
